package com.zee.home.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zee.common.utils.TimeConvertUtil;
import com.zee.home.dao.UserTokenDao;
import com.zee.home.entity.UserToken;
import com.zee.home.service.IUserTokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.UUID;


@Service
public class UserTokenServiceImpl extends ServiceImpl<UserTokenDao, UserToken> implements IUserTokenService {
    @Autowired
    UserTokenDao userTokenDao;
    /**
     * 12小时后过期
     */
    private final static int EXPIRE = 3600 * 12;

    @Override
    public UserToken getByToken(String token) {
        return userTokenDao.getByToken(token);
    }

    @Override
    public UserToken createToken(Integer userId) {
        //当前时间
        Date now = new Date();
        //过期时间
        Date expireTime = new Date(now.getTime() + EXPIRE * 1000);

        //用户token
        String token;

        //判断是否生成过token
        UserToken userToken = userTokenDao.getByUserId(userId);
        if (userToken == null) {
            //生成一个token
            token = generateToken();

            userToken = new UserToken();
            userToken.setUserId(userId);
            userToken.setToken(token);
            userToken.setExpireTime(TimeConvertUtil.toLocalDateTime(expireTime));

            //保存token
            userTokenDao.insert(userToken);
        } else {
            //判断token是否过期
            if (TimeConvertUtil.getMillisTime(userToken.getExpireTime()) < System.currentTimeMillis()) {
                //token过期，重新生成token
                token = generateToken();
            } else {
                token = userToken.getToken();
            }

            userToken.setToken(token);
            userToken.setExpireTime(TimeConvertUtil.toLocalDateTime(expireTime));

            //更新token
            this.updateById(userToken);
        }

        return userToken;
    }

    @Override
    public void expireToken(Integer userId) {

        UserToken userToken = new UserToken();
        userToken.setUserId(userId);
        userToken.setExpireTime(LocalDateTime.now());

        this.updateById(userToken);
    }

    private String generateToken() {
        return UUID.randomUUID().toString().replace("-", "");
    }
}
